package utils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;


public class UtilCollection {

	public static boolean isNullOrEmpty(Collection collection) {
		if(collection==null){
			return true;
		}
		if(collection.size()==0){
			return true;
		}
		return false;
	}
	
	public static <T extends Comparable<? super T>> String numberList2String(List<T> list,String orderType,String divider){
		String result="";
		if(UtilCollection.isNullOrEmpty(list)){
			return result;
		}
		Collections.sort(list);
		if(orderType.equalsIgnoreCase("asc")){
			for(T t:list){
				result+=t.toString()+divider;
			}
			result=UtilString.deleteTail(result, divider.length());
		}
		
		if(orderType.equalsIgnoreCase("desc")){
			for(int i=list.size()-1;i>=0;i--){
				result+=list.get(i).toString()+divider;
			}
			result=UtilString.deleteTail(result, divider.length());
		}
		return result;
	}
	
	public static  String Convert2String(List<String> list,String divider){
		String result;
		if(UtilString.isNullOrEmpty(divider)){
			throw new RuntimeException("divider is null or empty.");
		}
		if(list==null || list.size()==0){
			return "";
		}else {
			Collections.sort(list);
			StringBuffer stringBuffer=new StringBuffer();
			for(Object object:list){
				if(object!=null){
					stringBuffer.append(object.toString());
				}
				stringBuffer.append(divider);
			}
			result=stringBuffer.toString();
			result=UtilString.deleteTail(result, divider.length());
		}
		return result;
	}
	
	public static <T> T[] collection2Array(Class<T> clazz,Collection<T> collection) {
		T[] array=null;
		int size=0;
		if(!UtilCollection.isNullOrEmpty(collection)){
			size=collection.size();
		}
		array=(T[])Array.newInstance(clazz,size);
		int i=0;
		for(T t:collection){
			array[i]=t;
			i++;
		}
		return array;
	}
	
	public static void main(String...args){
		List<String> list=new ArrayList<String>();
		list.add("a");
		list.add("b");
		list.add("c");
		String[] strings=collection2Array(String.class,list);
		for(String s:strings){
			System.out.println(s);
		}
		
		List<Integer> integers=new ArrayList<>();
		integers.add(null);
		integers.add(2);
		integers.add(13);
		integers.add(0);
		String resultString=numberList2String(integers,"desc",",");
		System.out.println(resultString);
	}
}
